package com.xiaoxing.salesclient.mvp.ui.fragment;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.xiaoxing.salesclient.di.component.DaggerFragmentHomeComponent;
import com.xiaoxing.salesclient.di.module.FragmentHomeModule;
import com.xiaoxing.salesclient.mvp.contract.FragmentHomeContract;
import com.xiaoxing.salesclient.mvp.model.entity.Accept;
import com.xiaoxing.salesclient.mvp.model.entity.Complete;
import com.xiaoxing.salesclient.mvp.model.entity.ProcessList;
import com.xiaoxing.salesclient.mvp.model.entity.Transfered;
import com.xiaoxing.salesclient.mvp.presenter.FragmentHomePresenter;
import com.xiaoxing.salesclient.mvp.ui.adapter.SopLiuChengAdapter;
import com.xiaoxing.salesclient.mvp.ui.inter.ZhuangJie;
import com.xiaoxing.salesclient.mvp.ui.popup.ZhuanJiePopup;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.StatusBarUtil;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import xiaoxing.com.salesclient.R;
import xiaoxing.com.salesclient.R2;

public class FragmentHome extends BaseFragment<FragmentHomePresenter> implements FragmentHomeContract.View, EasyPermissions.PermissionCallbacks, ZhuangJie {

    private static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
    @BindView(R2.id.refreshLayout)
    RefreshLayout refreshLayout;

    @BindView(R2.id.empty)
    View mEmptyLayout;

    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty_text)
    TextView empty_text;

    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.title)
    TextView mTitle;

    @BindView(R2.id.btnRight)
    ImageView btnRight;

    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    private SopLiuChengAdapter mAdapter;
    private List<ProcessList.DataBean> mProcessListList = new ArrayList<>();

    private ZhuanJiePopup zhuanJiePopup;


    public static FragmentHome newInstance(String content) {

        Bundle args = new Bundle();
        args.putString("", content);
        FragmentHome fragment = new FragmentHome();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerFragmentHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .fragmentHomeModule(new FragmentHomeModule(this))
                .build()
                .inject(this);
    }


    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.sales_client_fragment_home, null);

        return view;
    }


    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        intervalTransfered();
        btnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_sao_miao));
        btnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ArmsUtils.snackbarText(getString(R.string.sales_client_zheng_zai_kai_fa_zhong));

                requestCodeQRCodePermissions();
            }
        });
        mTitle.setText("SOP流程");
        initEmptyText();
        initToolbar();
        initRefreshLayout();
        initRecyclerView();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
    }

    @AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private void requestCodeQRCodePermissions() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(getActivity(), perms)) {
            EasyPermissions.requestPermissions(this, "掃描二維碼需要打開相機和散光燈的權限", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
        } else {
            Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_SCAN_ACTIVITY);
        }
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(HuoDongListActivity.this, VERTICAL));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new SopLiuChengAdapter(getActivity(), mProcessListList));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Utils.navigation(getActivity(), RouterHub.SALES_CLIENT_GU_KE_DETAIL_ACTIVITY);
                mSharedPreferencesHelper.putString("ke_hu_uid", mProcessListList.get(position).getUid());
//                mSharedPreferencesHelper.putString("doctor_id", mProcessListList.get(position).getStaff_id());
//                mSharedPreferencesHelper.putBean("processList_DataBean", mProcessListList.get(position));

                ARouter.getInstance().build(RouterHub.SALES_CLIENT_GU_KE_DETAIL_ACTIVITY).withString("order_id", mProcessListList.get(position).getOrder_id()).navigation(getActivity());
            }
        });
    }

    private void initRefreshLayout() {
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));

        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getIndexData();
                refreshLayout.finishRefresh();

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore(0);
            }
        });
    }

    private void initToolbar() {
        toolbar.setNavigationIcon(null);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//            }
//        });

        //状态栏透明和间距处理
        StatusBarUtil.immersive(getActivity());
        StatusBarUtil.setPaddingSmart(getActivity(), toolbar);
    }

    private void initEmptyText() {
        empty_image.setImageResource(R.drawable.no_data);
        empty_text.setTextColor(getResources().getColor(R.color.public_no_data));
        empty_text.setText("暫無消息,下拉更新");
    }

    private void getIndexData() {
        mPresenter.processList(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));
    }

    @Override
    public void setData(@Nullable Object data) {
    }

    @Override
    public void processlistSuccess(ProcessList processList) {
        if (processList.getData() != null && processList.getData().size() > 0) {
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
            mProcessListList.clear();
            mProcessListList.addAll(processList.getData());
            mAdapter.notifyDataSetChanged();
        } else {

            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
            mProcessListList.clear();
            mProcessListList.addAll(processList.getData());
            mAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void transferedSuccessed(Transfered transfered) {

        if (transfered != null && transfered.getData() != null) {

            Transfered.DataBean dataBean = transfered.getData();


            if (zhuanJiePopup == null)
                zhuanJiePopup = new ZhuanJiePopup(getActivity(), FragmentHome.this, dataBean.getOrder_id(), dataBean.getTransfer_id(), "", dataBean.getNick_name());
            if (!zhuanJiePopup.isShowing()) {
                zhuanJiePopup.showPopupWindow();
            }
        }
    }

    @Override
    public void completeSuccessed(Complete complete) {
        ArmsUtils.snackbarText(complete.getMsg());
    }

    @Override
    public void acceptSuccessed(Accept accept) {
        ArmsUtils.snackbarText(accept.getMsg());
        refreshLayout.autoRefresh();
    }


    @Override
    public void showMessage(@NonNull String message) {

    }


    /**
     * 销毁时停止心跳
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    private static Disposable mDisposable;

    private void intervalTransfered() {

        Observable.interval(30, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NonNull Long number) {
                        mPresenter.transfered(mSharedPreferencesHelper.getString(BaseConstants.TOKEN));
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    @Override
    public void zhuanJie(String order_id, String staff_id) {
        mPresenter.accept(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), order_id, staff_id);

    }
}
